from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Optional
import os
from dotenv import load_dotenv
import requests
import json
import logging

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

# 加载环境变量
load_dotenv()

app = FastAPI(title="文本切片服务")

# 配置 CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 配置
API_TOKEN = os.getenv("SILICONFLOW_API_TOKEN")
API_URL = "https://api.siliconflow.cn/v1/chat/completions"

class TextSplitRequest(BaseModel):
    text: str
    chunk_size: int = 1000
    chunk_overlap: int = 200
    model: str = "Qwen/QwQ-32B"

@app.post("/split")
async def split_text(request: TextSplitRequest):
    if not API_TOKEN:
        raise HTTPException(status_code=500, detail="API token not configured")
    
    try:
        logger.debug(f"Request: {request.dict()}")
        
        # 构建提示词
        system_prompt = f"""你是一个专业的文本切片助手。请将给定的文本按照以下要求进行切片：
1. 每个切片的大小约为{request.chunk_size}个字符
2. 相邻切片之间的重叠部分约为{request.chunk_overlap}个字符
3. 尽量在句子的自然断点处进行切片
4. 返回JSON格式的切片结果，格式为：{{"chunks": ["切片1", "切片2", ...]}}"""

        # 构建请求数据
        headers = {
            "Authorization": f"Bearer {API_TOKEN}",
            "Content-Type": "application/json"
        }
        
        data = {
            "model": request.model,
            "messages": [
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": request.text}
            ],
            "temperature": 0.1
        }
        
        # 发送请求到硅基流动API
        response = requests.post(API_URL, headers=headers, json=data)
        response.raise_for_status()
        
        # 解析响应
        result = response.json()
        content = result["choices"][0]["message"]["content"]
        
        # 尝试解析JSON响应
        try:
            chunks = json.loads(content)
            return chunks
        except json.JSONDecodeError:
            # 如果返回的不是有效的JSON，直接返回文本内容
            return {"chunks": [content]}
        
    except Exception as e:
        logger.error(f"Error: {str(e)}", exc_info=True)
        raise HTTPException(status_code=500, detail=str(e))

@app.get("/")
async def root():
    return {"message": "欢迎使用文本切片服务"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8001, reload=True) 